//
//  ProfileEditNameView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 12.04.25.
//

import SwiftUI

struct ProfileEditGenderView: View {
    
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.presentToast) var presentToast
    
    @StateObject var viewModel = ProfileEditGenderViewModel()
    @State var gender: Int = 1
    
    var body: some View {
        VStack (alignment: .leading) {
            Button (action: {
                gender = 1
            }) {
                HStack {
                    Text("男")
                        .font(.system(size: 16)).foregroundColor(Color.koiColorTitle)
                    Spacer()
                    if gender == 1 {
                        Image("koi_ic_check")
                            .resizable()
                            .frame(width: 16, height: 16)
                    }
                    
                }
                .padding(EdgeInsets(top: 20, leading: 16, bottom: 20, trailing: 16))
                .background(Color.koiColorBackgroundItem)
                .cornerRadius(16)
                .padding(.top, 20)
            }
            
            Button(action: {
                gender = 2
            }) {
                HStack {
                    Text("女")
                        .font(.system(size: 16)).foregroundColor(Color.koiColorTitle)
                    Spacer()
                    if gender == 2 {
                        Image("koi_ic_check")
                            .resizable()
                            .frame(width: 16, height: 16)
                    }
                }
                .padding(EdgeInsets(top: 20, leading: 16, bottom: 20, trailing: 16))
                .background(Color.koiColorBackgroundItem)
                .cornerRadius(16)
            }

            Spacer()
        }
        .padding(.horizontal, 20)
        .koiToolbar(title: Text("编辑性别"))
        .navigationBarItems(trailing: Button(action:{
            // 确定修改性别
        }){
            Button(action: genderModify) {
                Text("确定").font(.system(size: 14)).foregroundColor(Color.koiColorPrimary)
            }
        })
        .onChange(of: viewModel.state) { value in
            if value == "" {
                return
            }
            if value == "success" {
                presentToast(.init(message: "修改成功"))
                presentationMode.wrappedValue.dismiss()
            } else {
                presentToast(.init(message: value))
            }
            viewModel.state = ""
        }
        .onAppear {
            if let user = KoiAccountingUserManager.standard.user() {
                gender = user.sex ?? 1
            }
        }
    }
    
    private func genderModify() {
        viewModel.genderModify(gender: gender)
    }
}

#Preview {
    ProfileEditGenderView()
}
